using ERPWinFormWork.Product;
using ERPWinFormWork.Sales.DTO;
using ERPWinFormWork.Sales.DTO.Output;
using ERPWinFormWork.Sales.ErrorCode;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ERPWinFormWork.Sales
{
    public partial class CustomerPriceAddForm : Form
    {
        private ApiClient _apiClient;
        private Form1 form1;
        public CustomerPriceAddForm(Form1 form1)
        {
            InitializeComponent();
            _apiClient = new ApiClient(AppConfig.ApiBaseUrl);
            GetProductSelect();
            GetCustomerSelect();
            this.form1 = form1;
        }



        private async void GetProductSelect()
        {
            var response = await _apiClient.GetAsync<ERPWinFormWork.Sales.ErrorCode.ApiResponse<List<ProductModel>>>(
                    endpoint: "Sales/ProductGet"
                );
            if (response != null && response.code == 200)
            {
                var customerList = new List<ProductModel>
                {
                    new ProductModel { Id = 0, Product_Name = "请选择" }
                };
                customerList.AddRange(response.data);
                cboProduct.DataSource = customerList;
                cboProduct.DisplayMember = "product_Name";//指定显示的字段
                cboProduct.ValueMember = "id";//绑定id属性
            }
        }

        private async void GetCustomerSelect()
        {
            var response = await _apiClient.GetAsync<ERPWinFormWork.Sales.ErrorCode.ApiResponse<List<Customer>>>(
                    endpoint: "Sales/CustomerGet"
                );
            if (response != null && response.code == 200)
            {
                var customerList = new List<Customer>
                {
                    new Customer { id = 0, Customer_Name = "请选择" }
                };
                customerList.AddRange(response.data);
                cboCustomer.DataSource = customerList;
                cboCustomer.DisplayMember = "Customer_Name";
                cboCustomer.ValueMember = "id";
                cboCustomer.SelectedIndex = 0;
            }
        }

        private async void btnAdd_Click(object sender, EventArgs e)
        {
            // 禁用按钮防止重复提交
            btnAdd.Enabled = false;
            try
            {
                // 1. 获取输入值
                string priceText = txtproductPrice.Text.Trim();
                string description = txtDescr.Text.Trim();
                var selectedCustomer = cboCustomer.SelectedItem as Customer;
                var selectedProduct = cboProduct.SelectedItem as ProductModel;

                // 2. 空值与格式校验
                if (string.IsNullOrWhiteSpace(priceText))
                {
                    MessageBox.Show("产品价格不能为空！", "校验失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                if (selectedCustomer == null || selectedCustomer.id <= 0)
                {
                    MessageBox.Show("请选择有效的客户！", "校验失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                if (selectedProduct == null || selectedProduct.Id <= 0)
                {
                    MessageBox.Show("请选择有效的产品！", "校验失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                if (string.IsNullOrWhiteSpace(description))
                {
                    MessageBox.Show("备注信息不能为空！", "校验失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // 3. 类型转换
                if (!decimal.TryParse(priceText, out decimal price) || price <= 0)
                {
                    MessageBox.Show("产品价格必须大于0！", "数据错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                // 4. 构建请求对象
                var customerPriceCommand = new CustomerPriceCommandCommandDTO
                {
                    customerPriceCommandDTO = new CustomerPriceCommandDTO
                    {
                        Customer_Descr = description,
                        Customer_Id = selectedCustomer.id,
                        Price = price,
                        Product_Id = selectedProduct.Id
                    }
                };

                // 5. 发送请求并处理响应
                var response = await _apiClient.PostAsync<CustomerPriceCommandCommandDTO, ApiResponse<string>>(
                    endpoint: "Sales/CustomerPriceAdd",
                    data: customerPriceCommand
                );

                if (response != null && response.code == 200)
                {
                    MessageBox.Show($"客户价格添加成功！\n客户：{selectedCustomer.Customer_Name}\n产品：{selectedProduct.Product_Name}\n价格：{price:C}", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    form1?.GetDataCustomerPrice(); // 刷新父窗体数据
                    this.Close();
                }
                else
                {
                    MessageBox.Show($"提交失败：{response?.msg ?? "未知错误"}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"系统错误：{ex.Message}", "系统错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                // 无论成功失败，都重新启用按钮
                btnAdd.Enabled = true;
            }
        }

        private void cboProduct_SelectedIndexChanged(object sender, EventArgs e)
        {
            var selectedProduct = cboProduct.SelectedItem as ProductModel;
            if (selectedProduct != null)
            {
                txtProductNumber.Text = selectedProduct.Product_Number ?? "";
                txtProductS.Text = selectedProduct.Specification ?? "";
            }
            else
            {
                txtProductNumber.Text = "";
                txtProductS.Text = "";
            }
        }
    }
}
